const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const path = require('path');
const http = require('http');
const { WebSocketServer } = require('ws');
require('dotenv').config();
const User = require('./models/User');
const LogModel = require('./models/Log');

const app = express();
const server = http.createServer(app);
const PORT = process.env.PORT || 8080;

// 识别反向代理后的真实 IP/协议
app.set('trust proxy', true);

// 全局结构化访问日志（覆盖本地路由与代理）
app.use(async (req, res, next) => {
  const start = Date.now();
  const getClientIp = () => {
    const xff = req.headers['x-forwarded-for'];
    if (typeof xff === 'string' && xff.length) return xff.split(',')[0].trim();
    return req.ip || req.connection?.remoteAddress || '';
  };
  let userId = null, phone = null;
  try {
    const auth = req.headers.authorization || req.headers.Authorization;
    const m = typeof auth === 'string' ? auth.match(/bearer\s+(.*)/i) : null;
    const token = m ? m[1] : null;
    if (token) { const u = await User.verifyToken(token); userId = u?.id || null; phone = u?.phone || null; }
  } catch {}
  res.on('finish', () => {
    const payload = {
      level: 'INFO', type: 'access', method: req.method, path: req.originalUrl || req.url,
      status: res.statusCode, duration_ms: Date.now() - start, ip: getClientIp(), ua: req.headers['user-agent'] || '', userId, phone,
      time: new Date().toISOString(),
    };
    // console.log(JSON.stringify(payload));
    // 持久化访问日志（失败不影响主流程）
    LogModel.logAccess(payload).catch(() => {});
  });
  next();
});

// CORS（允许前端跨域访问包含图片在内的资源）
app.use(cors({
  origin: '*',
  methods: ['GET','HEAD','PUT','PATCH','POST','DELETE','OPTIONS'],
  allowedHeaders: ['Content-Type','Authorization','Accept','Origin'],
}));

// 安全中间件
// app.use(helmet({
//   crossOriginResourcePolicy: { policy: "cross-origin" }
// }));



// 请求日志
// app.use(morgan('combined'));

// 解析请求体
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 静态文件服务（用于访问图片等上传内容）
app.use('/storage', express.static(path.join(__dirname, '../storage'), {
  setHeaders: (res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');
  }
}));




// 本地接口（先于代理挂载）
const authRouter = require('./routes/auth');
const vehiclesRouter = require('./routes/vehicles');
const proxyRouter = require('./routes/proxy');
app.use('/api/auth', authRouter);
app.use('/api/vehicles', vehiclesRouter);
app.use('/api/proxy', proxyRouter);
// 兼容开发代理将 /api 前缀重写掉后的路径
app.use('/proxy', proxyRouter);

// 通用代理中间件 - 处理所有其他API请求（作为兜底）
const { axiosProxy } = require('./middleware/universal-proxy');
app.use('/', async (req, res) => {
  // 移除 /api 前缀
  req.path = req.originalUrl.replace(/^\/api/, '');
  await axiosProxy(req, res);
});

// WebSocket: 星火大模型代理
const { handleClientWS } = require('./ws/spark-proxy');
const wss = new WebSocketServer({ noServer: true });

server.on('upgrade', (req, socket, head) => {
  // 仅处理 /ws/spark 路径
  if (req.url && req.url.startsWith('/ws/spark')) {
    wss.handleUpgrade(req, socket, head, (ws) => {
      handleClientWS(ws, req);
    });
  } else {
    socket.destroy();
  }
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    code: '40400',
    message: '接口不存在',
    data: null,
    timestamp: new Date().toISOString()
  });
});


// 启动服务器
server.listen(PORT, () => {
  console.log(`🚀 服务启动成功`);
  // console.log(`📍 服务地址: http://localhost:${PORT}`);
  // console.log(`🔍 健康检查: http://localhost:${PORT}/health`);
  // console.log(`🌐 环境: ${process.env.NODE_ENV || 'development'}`);
});

module.exports = app;
